#include "statistics.h"

#define MAX_STATISTICS_CNT 10

statistics_t statistics[MAX_STATISTICS_CNT] = {0};
uint32_t statistics_cnt = 0;

int statistics_register(const char* name,uint32_t period)
{
	if( name == NULL || period == 0)
	{
		return -1;
	}
	
	if( statistics_cnt >= MAX_STATISTICS_CNT )
	{
		return -2;
	}
	
	statistics[statistics_cnt].name = name;
	statistics[statistics_cnt].index = statistics_cnt;
	statistics[statistics_cnt].period = period;
	statistics[statistics_cnt].cnt = 0;
	statistics[statistics_cnt].lastest_tick = 0;
	statistics[statistics_cnt].max_cnt = 0;
	statistics[statistics_cnt].min_cnt = UINT32_MAX;
	statistics[statistics_cnt].average_cnt = 0;
	statistics[statistics_cnt].frequence = 0;
	statistics[statistics_cnt].n = 1;
	statistics_cnt++;
	/* initial */
	
	return 0;
}	


int statistics_update(const char *name)
{
	if( name == NULL )
	{
		return -1;
	}
	
	int i = 0;
	
	for(i = 0;i < statistics_cnt;i++)
	{
		if( strcmp(statistics[i].name,name) == 0 )
		{
			statistics[i].cnt++;
		}		
	}
	
	if( i == statistics_cnt )
	{
		return -2;
	}
	return 0;
}


void statistics_monitor( void )
{
	int i = 0;
	uint32_t time = 0;
	
	time = HAL_GetTick();
	
	for( i = 0;i < statistics_cnt; i++)
	{
		if( (time - statistics[i].lastest_tick) >= statistics[i].period )
		{
			if( statistics[i].cnt > statistics[i].max_cnt )
			{
				statistics[i].max_cnt = statistics[i].cnt;
				/*update max cnt*/
			}
			else if( statistics[i].cnt < statistics[i].min_cnt )
			{
				statistics[i].min_cnt = statistics[i].cnt;
				/*update min cnt*/
			}
			

			statistics[i].average_cnt = statistics[i].average_cnt + 1.f/(float)statistics[i].n * (statistics[i].cnt - statistics[i].average_cnt);
			/*update average cnt - hat(an) = hat(an-1) + (1/n * (an - hat(an-1)))*/
			statistics[i].n++;
			/*update n*/
			statistics[i].frequence = statistics[i].average_cnt / ((float)(time - statistics[i].lastest_tick) / 1000.f);
			/* calculate frequnce of update*/
			statistics[i].cnt = 0;
			/* reset cnt */
			
			statistics[i].lastest_tick = time;
			/*update tick*/
		}
	}
}

